package com.example.abc.util;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.example.abc.common.Constants;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

/**
 * 阿里云OSS操作工具类
 * Created by Peter on 2017/4/19.
 */
public class AliyunOssUtil {
    public static final Logger logger = LoggerFactory.getLogger(AliyunOssUtil.class);

    public final static OSSClient client = new OSSClient(Constants.ossEndpoint, Constants.ossAccessKeyId, Constants.ossAccessKeySecret);

    public static String toFullOssUrl(String url) {
        if (StringUtils.isBlank(url)) {
            return url;
        }
        if (url.startsWith("http://") || url.startsWith("https://")) {
            return url;
        }
        return Constants.ossDomain + url;
    }
        /**
         * 获取文件的后缀名，如fileName="test.png"，返回".png"。
         *
         * @param fileName
         * @return 文件的后缀名，包含"."
         * @throws Exception
         */
    public static String getFileSuffix(String fileName) throws Exception {
        if (fileName == null || "".equals(fileName.trim())) {
            throw new Exception("文件名不能为空");
        }
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        return suffix;
    }

    /**
     * 获取文件名，不包含后缀
     *
     * @param fileName
     * @return
     * @throws Exception
     */
    public static String getFilePrefix(String fileName) throws Exception {
        if (fileName == null || "".equals(fileName.trim())) {
            throw new Exception("文件名不能为空");
        }
        String suffix = fileName.substring(0, fileName.lastIndexOf("."));
        return suffix;
    }

    /**
     * 根据给定的文件名，返回带后缀的随机文件名，格式：uuid+原后缀名
     *
     * @param fileName
     * @return
     * @throws Exception
     */
    public static String getRandomFileName(String fileName) throws Exception {
        if (fileName == null || "".equals(fileName.trim())) {
            throw new Exception("文件名不能为空");
        }
        String uuid = UUID.randomUUID().toString();
        String name = uuid + getFileSuffix(fileName);
        return name;
    }

    public static void upload(String key, InputStream inputStream, long size) {
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(size);
        client.putObject(Constants.ossBucketName, key, inputStream);
    }
}
